package com.xinke.query.common.result;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinke.query.common.utils.GaoSuInfoUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * 全局统一返回结果类
 */
@Data
@Slf4j
public class Result<T> {


    // 静态ObjectMapper实例，全局复用
    private static final ObjectMapper objectMapper = new ObjectMapper();

    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private T data;

    public Result() {
    }

    private static <T> Result<T> build(T data) {
        Result<T> result = new Result<>();
        if (data != null)
            result.setData(data);
        return result;
    }

    public static <T> Result<T> build(T body, Integer code, String message) {
        Result<T> result = build(body);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }


    public static <T> Result<T> ok(T data) {
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static <T> Result<T> ok() {
        return Result.ok(null);
    }

    public static <T> Result<T> fail() {
        return build(null, ResultCodeEnum.FAIL);
    }

    public static <T> Result<T> fail(ResultCodeEnum codeEnum) {
        return build(null, codeEnum);
    }

    public static <T> Result<T> fail(ResultCodeEnum codeEnum, String errorMsg) {
        return build(null, codeEnum.getCode(), codeEnum.getMessage() + ":" + errorMsg);
    }

    public static <T> Result<T> fail(Integer code, String message) {
        return build(null, code, message);
    }

    public static Result fail(ResultCodeEnum paramValidationFailed, HashMap<String, String> errors) {
        return fail(paramValidationFailed, GaoSuInfoUtils.mapToString(errors));
    }

}
